#include "MarkdownAdaptor.h"

#include <QJsonObject>

MarkdownAdaptor::MarkdownAdaptor(shell::Access_interface & /*shell_access*/)
{
    _edit = new MarkdownViewer;
    _edit->setReadOnly(true);
}

QWidget* MarkdownAdaptor::panel_widget()
{
    return _edit;
}

QString MarkdownAdaptor::title() const
{
    return _title;
}

bool isSpace(QChar ch)
{
    return ch == '\r' || ch == '\n' || ch == ' ' || ch == '\t';
}

bool MarkdownAdaptor::acceptData(const QJsonObject & data)
{
    auto it = data.find("text");
    if (it == data.end())
        return false;

    QString text   = it->toString();  
    int     line   = 1;

    it = data.find("file");
    if (it != data.end())
        _title = it->toString();

    it = data.find("line");
    if (it != data.end())
        line = it->toInt();

    int block_count = 0;
    int line_count  = 1;
    int block_begin = 0;

    while(block_begin < text.length()) {
        if (!isSpace(text[block_begin]))
            break;
        block_begin ++;
    }

    while(line_count < line) {
        block_begin = text.indexOf('\n', block_begin);
        if (block_begin < 0)
            break;
        line_count ++;

        block_begin ++;
        bool block = false;

        while(block_begin < text.length()) {
            if (text[block_begin] == '\n') {
                block = true;
                line_count ++;
            }

            if (!isSpace(text[block_begin])) {
                if (text[block_begin].isDigit() || text[block_begin] == '*')
                    block = true;
                break;
            }

            block_begin ++;
        }
        
        if (block)
            block_count ++;
    }

    _edit->setMarkdown(text);
    
    QTextCursor cursor = _edit->textCursor();

    cursor.movePosition(QTextCursor::Start);
    cursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor, block_count);
    // cursor.select(QTextCursor::WordUnderCursor);
    _edit->setTextCursor(cursor);

    int height = _edit->size().height();
        
    _edit->resize(_edit->size().width(), height-1);
    _edit->resize(_edit->size().width(), height);

    return true;
}

